package com.pcbly.web.persistence.role;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;


import com.pcbly.web.bean.system.RoleBean;
import com.pcbly.web.components.utils.random.GUID;
import com.pcbly.web.persistence.HibernateBaseDao;

public class RoleHibernateDao extends HibernateBaseDao<RoleBean> implements
		RoleDao {
	public RoleHibernateDao() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -9008191573151766279L;

	protected Class<RoleBean> getEntityClass() {
        return RoleBean.class;
    }
	@SuppressWarnings("unchecked")
	public List<RoleBean> queryRoleBeansByUserId(String userId)
			throws Exception {
		// TODO Auto-generated method stub
		String hsql = "select a from RoleBean a inner join a.users b where b.userId=:userid";
		List<RoleBean> list = getHibernateTemplate().find(hsql, userId);

		return list;
	}

	@SuppressWarnings("unchecked")
	public List<RoleBean> queryRoleBeansByAuthorityId(String authorityId)
			throws Exception {
		// TODO Auto-generated method stub
		String hsql = "from RoleBean a inner join  a.auths b where b.authorityId=:authorityId";
		List<RoleBean> list = getHibernateTemplate().find(hsql, authorityId);

		return list;
	}

	@SuppressWarnings("unchecked")
	public List<RoleBean> findBy(Map<String, String> filter)throws Exception {
		Criteria criteria = getEntityCriteria();

		String id = filter.get("id");
		if (StringUtils.isNotBlank(id))
			criteria.add(Restrictions.eq("id", id));

		String name = filter.get("name");
		if (StringUtils.isNotBlank(name))
			criteria.add(Restrictions.like("name", "%" + name + "%"));

		criteria.addOrder(org.hibernate.criterion.Order.asc("id"));

		return criteria.list();
	}
	@Override
	public void saveRoleBean(RoleBean bean) throws Exception {
		// TODO Auto-generated method stub
		String id=(new GUID()).toString();
		bean.setId(id);
		getHibernateTemplate().save(bean);
		
	}
}
